﻿using FTBS.Models.BLO;
using FTBS.Models.Entities;
using FTBS.Models.Entities.Concert;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Objects;
using System.Linq;
using System.Transactions;
using System.Web;

namespace FTBS.Models.DAO
{
    public class AdminDAO
    {
        private FilmTicketBookingSystemEntities _entities = new FilmTicketBookingSystemEntities();
        private PromotionBLO _promotionBlo = new PromotionBLO();
        private ShowTimeBLO _showtimeBlo = new ShowTimeBLO();

        /// <summary>
        /// Delete all promotions have ToDay over current day
        /// </summary>
        /// <returns></returns>
        /// <author>VuongVT</author>
        public AdminHomeInfoConcertEntity DeleteAllPromotionOverDay()
        {
            try
            {
                AdminHomeInfoConcertEntity adminHomeInfor = new AdminHomeInfoConcertEntity();

                List<ScheduleConcertEntity> listScheduleDelete = new List<ScheduleConcertEntity>();
                List<Promotion> listPromotionDelete = new List<Promotion>();

                using (TransactionScope ts = new TransactionScope())
                {
                    try
                    {
                        var resultQuery = from promotion in _entities.Promotions
                                          where promotion.IsDeleted == false
                                                && promotion.ToDate < DateTime.Today
                                          select promotion;

                        int totalPromotionDelete = 0;
                        int totalScheduleDelete = 0;
                        int totalTicket = 0;

                        foreach (var promotion in resultQuery)
                        {
                            promotion.IsDeleted = true;
                            _entities.Entry(promotion).State = EntityState.Modified;
                            int resultUpdatePromotion = _entities.SaveChanges();
                            totalPromotionDelete = totalPromotionDelete + 1;
                            listPromotionDelete.Add(promotion);

                            var searchSchedule = from schedule in _entities.Schedules
                                                 where schedule.IsDeleted == false
                                                       && schedule.PromotionId == promotion.PromotionId
                                                 select schedule;
                            foreach (var schedule in searchSchedule)
                            {
                                schedule.IsDeleted = true;
                                _entities.Entry(schedule).State = EntityState.Modified;
                                int resultUpdateSchedule = _entities.SaveChanges();
                                totalScheduleDelete = totalScheduleDelete + 1;
                                ScheduleConcertEntity scheduleEntity = new ScheduleConcertEntity();
                                scheduleEntity.ScheduleId = schedule.ScheduleId;

                                //Get RoomName of room is deleted
                                var roomDelete = _entities.Rooms.Where(r => r.RoomId == schedule.RoomId).FirstOrDefault();
                                //Add roomName into scheduleDelete entity to show in the Staff Page
                                scheduleEntity.RoomName = roomDelete.RoomName;

                                //Get RoomName of room is deleted
                                var theaterDelete = _entities.Theaters.Where(r => r.TheaterId == schedule.TheaterId).FirstOrDefault();
                                //Add roomName into scheduleDelete entity to show in the Staff Page
                                scheduleEntity.TheaterName = theaterDelete.TheaterName;

                                //Get FilmName of film is deleted
                                var filmDelete = _entities.Films.Where(f => f.FilmId == schedule.FilmId).FirstOrDefault();
                                //Add roomName into scheduleDelete entity to show in the Staff Page
                                scheduleEntity.FilmName = filmDelete.Name;

                                scheduleEntity.Date = schedule.Date;

                                ShowTime showTimeOfSchedule = new ShowTime();
                                var resultShowTime = (from showTime in _entities.ShowTimes
                                                      where showTime.ShowTimeId == schedule.ShowTimeId
                                                            && showTime.IsDeleted == false
                                                      select showTime).FirstOrDefault();
                                showTimeOfSchedule = resultShowTime;
                                var strTime = string.Empty;
                                if (showTimeOfSchedule.Time.Hours < 10)
                                {
                                    strTime = strTime + "0" + showTimeOfSchedule.Time.Hours;
                                }
                                else
                                {
                                    strTime = strTime + showTimeOfSchedule.Time.Hours;
                                }

                                if (showTimeOfSchedule.Time.Minutes < 10)
                                {
                                    strTime = strTime + " : " + "0" + showTimeOfSchedule.Time.Minutes;
                                }
                                else
                                {
                                    strTime = strTime + " : " + showTimeOfSchedule.Time.Minutes;
                                }
                                scheduleEntity.TimeForShow = strTime;
                                listScheduleDelete.Add(scheduleEntity);

                                //Delete all ticket have schedule which is over current day
                                var resultListTicket = from ticket in _entities.Tickets
                                                       where ticket.IsDeleted == false
                                                             && ticket.ScheduleId == schedule.ScheduleId
                                                             && schedule.IsDeleted == false
                                                       select ticket;

                                foreach (var ticket in resultListTicket)
                                {
                                    //Count total ticket is deleted
                                    totalTicket = totalTicket + 1;

                                    ticket.IsDeleted = true;
                                    _entities.Entry(ticket).State = EntityState.Modified;
                                    int resultUpdateTicket = _entities.SaveChanges();
                                }
                            }
                        }

                        adminHomeInfor.TotalScheduleDelete = totalScheduleDelete;
                        adminHomeInfor.TotalPromotionDelete = totalPromotionDelete;
                        adminHomeInfor.TotalTicketDelete = totalTicket;
                        adminHomeInfor.ListScheduleDelete = listScheduleDelete;
                        adminHomeInfor.ListPromotion = listPromotionDelete;

                        ts.Complete();
                    }
                    catch (Exception)
                    {
                        ts.Dispose();
                    }
                }
                return adminHomeInfor;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        /// <summary>
        /// Delete all schedule if schedule have showtime over the current day
        /// </summary>
        /// <param name="theater"></param>
        public AdminHomeInfoConcertEntity DeleteAllShowTimeAndScheduleAndTicketOverCurrentDay(Theater theater)
        {
            try
            {
                AdminHomeInfoConcertEntity adminHomeInfor = new AdminHomeInfoConcertEntity();

                DateTime currentDateTime = DateTime.Now;

                using (TransactionScope ts = new TransactionScope())
                {
                    try
                    {
                        //Get all schedule <= current day to Delete
                        var resultSchedule = _entities.Schedules.Where(schedule => schedule.TheaterId == theater.TheaterId
                                                                               && schedule.Date <= currentDateTime
                                                                               && schedule.IsDeleted == false);

                        //Count total schedule is deleted
                        int totalSchedule = 0;
                        //Count total ticket is deleted
                        int totalTicket = 0;

                        List<ScheduleConcertEntity> listScheduleDelete = new List<ScheduleConcertEntity>();

                        //Add theater name
                        adminHomeInfor.TheaterNameDelete = theater.TheaterName;

                        //Delete schedule over current day
                        foreach (var schedule in resultSchedule)
                        {
                            //ShowTime showTimeOfSchedule = new ShowTime();
                            //var resultQuery = (from showTime in _entities.ShowTimes
                            //                   where showTime.ShowTimeId == schedule.ShowTimeId
                            //                         && showTime.IsDeleted == false
                            //                   select showTime).FirstOrDefault();
                            //showTimeOfSchedule = resultQuery;

                            ScheduleConcertEntity scheduleDeleted = new ScheduleConcertEntity();

                            #region Delete ShowTime

                            //if (schedule.Date.Day == currentDateTime.Day && showTimeOfSchedule.Time.Hours < currentDateTime.Hour)
                            //{
                            //    //Delete a schedule over Current day
                            //    schedule.IsDeleted = true;
                            //    _entities.Entry(schedule).State = EntityState.Modified;
                            //    int resultUpdate = _entities.SaveChanges();
                            //    totalSchedule = totalSchedule + 1;

                            //    //Add ScheduleId and TimeForShow into scheduleDeleted entity to show in the Staff Page
                            //    scheduleDeleted.ScheduleId = schedule.ScheduleId;
                            //    scheduleDeleted.Date = schedule.Date;
                            //    var strTime = string.Empty;
                            //    if (showTimeOfSchedule.Time.Hours < 10)
                            //    {
                            //        strTime = strTime + "0" + showTimeOfSchedule.Time.Hours;
                            //    }
                            //    else
                            //    {
                            //        strTime = strTime + showTimeOfSchedule.Time.Hours;
                            //    }

                            //    if (showTimeOfSchedule.Time.Minutes < 10)
                            //    {
                            //        strTime = strTime + " : " + "0" + showTimeOfSchedule.Time.Minutes;
                            //    }
                            //    else
                            //    {
                            //        strTime = strTime + " : " + showTimeOfSchedule.Time.Minutes;
                            //    }
                            //    scheduleDeleted.TimeForShow = strTime;
                            //}
                            //else if (schedule.Date.Day < currentDateTime.Day)
                            //{
                            //    //Delete a schedule over Current day
                            //    schedule.IsDeleted = true;
                            //    _entities.Entry(schedule).State = EntityState.Modified;
                            //    int resultUpdate = _entities.SaveChanges();
                            //    totalSchedule = totalSchedule + 1;

                            //    //Add ScheduleId and TimeForShow into scheduleDeleted entity to show in the Staff Page
                            //    scheduleDeleted.ScheduleId = schedule.ScheduleId;
                            //    scheduleDeleted.Date = schedule.Date;
                            //    var strTime = string.Empty;
                            //    if (showTimeOfSchedule.Time.Hours < 10)
                            //    {
                            //        strTime = strTime + "0" + showTimeOfSchedule.Time.Hours;
                            //    }
                            //    else
                            //    {
                            //        strTime = strTime + showTimeOfSchedule.Time.Hours;
                            //    }

                            //    if (showTimeOfSchedule.Time.Minutes < 10)
                            //    {
                            //        strTime = strTime + " : " + "0" + showTimeOfSchedule.Time.Minutes;
                            //    }
                            //    else
                            //    {
                            //        strTime = strTime + " : " + showTimeOfSchedule.Time.Minutes;
                            //    }
                            //    scheduleDeleted.TimeForShow = strTime;
                            //}

                            #endregion

                            //Delete Schedule, if Date == current Date => compare Hour, if hour < current hour => Delete, else, not delete
                            if (schedule.Date == currentDateTime.Date)
                            {
                                if (schedule.Date.Hour < currentDateTime.Date.Hour)
                                {
                                    //First, Delete Schedule
                                    schedule.IsDeleted = true;
                                    _entities.Entry(schedule).State = EntityState.Modified;
                                    int resultUpdate = _entities.SaveChanges();
                                    scheduleDeleted.ScheduleId = schedule.ScheduleId;
                                    scheduleDeleted.FilmId = schedule.FilmId;
                                    scheduleDeleted.RoomId = schedule.RoomId;
                                    scheduleDeleted.ShowTimeId = schedule.ScheduleId;
                                    scheduleDeleted.Date = schedule.Date;
                                    scheduleDeleted.TheaterId = schedule.TheaterId;
                                    scheduleDeleted.PromotionId = schedule.PromotionId;
                                    scheduleDeleted.UserName = schedule.UserName;
                                    scheduleDeleted.IsActive = schedule.IsActive;
                                    scheduleDeleted.IsDeleted = schedule.IsDeleted;
                                    scheduleDeleted.IsCreateTicket = schedule.IsCreateTicket;
                                    totalSchedule = totalSchedule + 1;
                                }
                            }
                            else
                            {
                                //First, Delete Schedule
                                schedule.IsDeleted = true;
                                _entities.Entry(schedule).State = EntityState.Modified;
                                int resultUpdate = _entities.SaveChanges();
                                scheduleDeleted.ScheduleId = schedule.ScheduleId;
                                scheduleDeleted.FilmId = schedule.FilmId;
                                scheduleDeleted.RoomId = schedule.RoomId;
                                scheduleDeleted.ShowTimeId = schedule.ScheduleId;
                                scheduleDeleted.Date = schedule.Date;
                                scheduleDeleted.TheaterId = schedule.TheaterId;
                                scheduleDeleted.PromotionId = schedule.PromotionId;
                                scheduleDeleted.UserName = schedule.UserName;
                                scheduleDeleted.IsActive = schedule.IsActive;
                                scheduleDeleted.IsDeleted = schedule.IsDeleted;
                                scheduleDeleted.IsCreateTicket = schedule.IsCreateTicket;
                                totalSchedule = totalSchedule + 1;
                            }


                            //Get RoomName of room is deleted
                            var roomDelete = _entities.Rooms.Where(r => r.RoomId == schedule.RoomId).FirstOrDefault();
                            //Add roomName into scheduleDelete entity to show in the Staff Page
                            scheduleDeleted.RoomName = roomDelete.RoomName;

                            //Get FilmName of film is deleted
                            var filmDelete = _entities.Films.Where(f => f.FilmId == schedule.FilmId).FirstOrDefault();
                            //Add roomName into scheduleDelete entity to show in the Staff Page
                            scheduleDeleted.FilmName = filmDelete.Name;

                            //Delete all ticket have schedule which is over current day
                            var resultListTicket = from ticket in _entities.Tickets
                                                   where ticket.IsDeleted == false
                                                         && ticket.Status == false
                                                         && ticket.ScheduleId == schedule.ScheduleId
                                                         && schedule.IsDeleted == false
                                                   select ticket;

                            foreach (var ticket in resultListTicket)
                            {
                                //Count total ticket is deleted
                                totalTicket = totalTicket + 1;

                                ticket.IsDeleted = true;
                                _entities.Entry(ticket).State = EntityState.Modified;
                                int resultUpdateTicket = _entities.SaveChanges();
                            }
                            listScheduleDelete.Add(scheduleDeleted);
                        }

                        adminHomeInfor.TotalScheduleDelete = totalSchedule;
                        adminHomeInfor.TotalTicketDelete = totalTicket;
                        adminHomeInfor.ListScheduleDelete = listScheduleDelete;

                        ts.Complete();
                    }
                    catch (Exception)
                    {
                        ts.Dispose();
                    }
                }
                return adminHomeInfor;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// Get list Schedule have to create ticket.
        /// If schedule have Date == current day + deadline for create ticket => Get this schedule
        /// </summary>
        /// <param name="theater"></param>
        /// <returns></returns>
        /// <author>VuongVT</author>
        public AdminHomeInfoConcertEntity GetListHaveToCreateTicket(Theater theater)
        {
            try
            {
                AdminHomeInfoConcertEntity adminHomeInfor = new AdminHomeInfoConcertEntity();

                //Get Deadline for createTicket value
                DateTime deadLine = DateTime.Today.AddDays(theater.DeadlineCreateTicket);

                var resultSchedule = from schedule in _entities.Schedules
                                     where schedule.TheaterId == theater.TheaterId
                                           && schedule.IsDeleted == false
                                           && schedule.Date == deadLine
                                           && schedule.IsCreateTicket == false
                                     select schedule;
                List<ScheduleConcertEntity> listSchedule = new List<ScheduleConcertEntity>();
                int countSchedule = 0;

                foreach (var schedule in resultSchedule)
                {
                    //Get RoomName of room need to create ticket
                    var roomCreateTicket = _entities.Rooms.Where(r => r.RoomId == schedule.RoomId).FirstOrDefault();

                    ScheduleConcertEntity scheduleEntity = new ScheduleConcertEntity();
                    scheduleEntity.ScheduleId = schedule.ScheduleId;
                    scheduleEntity.FilmName = schedule.Film.Name;
                    scheduleEntity.Date = schedule.Date;

                    ShowTime showTimeOfSchedule = new ShowTime();
                    var resultQuery = (from showTime in _entities.ShowTimes
                                       where showTime.ShowTimeId == schedule.ShowTimeId
                                             && showTime.IsDeleted == false
                                       select showTime).FirstOrDefault();
                    showTimeOfSchedule = resultQuery;
                    var strTime = string.Empty;
                    if (showTimeOfSchedule.Time.Hours < 10)
                    {
                        strTime = strTime + "0" + showTimeOfSchedule.Time.Hours;
                    }
                    else
                    {
                        strTime = strTime + showTimeOfSchedule.Time.Hours;
                    }

                    if (showTimeOfSchedule.Time.Minutes < 10)
                    {
                        strTime = strTime + " : " + "0" + showTimeOfSchedule.Time.Minutes;
                    }
                    else
                    {
                        strTime = strTime + " : " + showTimeOfSchedule.Time.Minutes;
                    }
                    scheduleEntity.TimeForShow = strTime;

                    scheduleEntity.RoomName = roomCreateTicket.RoomName;
                    listSchedule.Add(scheduleEntity);
                    countSchedule = countSchedule + 1;
                }
                adminHomeInfor.TheaterNameDelete = theater.TheaterName;
                adminHomeInfor.ListScheduleDelete = listSchedule;
                adminHomeInfor.TotalScheduleDelete = countSchedule;
                adminHomeInfor.DeadLineForCreateTicket = DateTime.Today;
                return adminHomeInfor;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// Get list payment have to confirm
        /// </summary>
        /// <param name="theater"></param>
        /// <returns></returns>
        public AdminHomeInfoConcertEntity GetListPaymentHaveToConfirm()
        {
            try
            {
                AdminHomeInfoConcertEntity adminHomeInfor = new AdminHomeInfoConcertEntity();
                List<PaymentConcertEntity> listPayment = new List<PaymentConcertEntity>();
                var selectPayment = from payment in _entities.Payments
                                    where payment.IsComplete == true
                                          && payment.ConfirmPerson == null
                                    select payment;
                foreach (var item in selectPayment)
                {
                    PaymentConcertEntity payment = new PaymentConcertEntity();
                    payment.PaymentId = item.PaymentId;
                    payment.ChargeMoney = item.ChargeMoney;
                    payment.CartId = item.CartId;
                    payment.ActualMoney = item.ActualMoney;
                    payment.ActualMoneyPaid = Convert.ToDouble(item.ActualMoney).ToString("0,000");
                    payment.PaidTime = item.PaidTime;
                    payment.FullName = item.FullName;
                    payment.BankAccount = item.BankAccount;
                    payment.PhoneNumber = item.PhoneNumber;
                    payment.Email = item.Email;
                    payment.IsComplete = item.IsComplete;
                    payment.ConfirmPerson = item.ConfirmPerson;
                    payment.IsDeleted = item.IsDeleted;
                    var selectTicketCart = (from ticketCart in _entities.TicketCarts
                                            where ticketCart.CartId == item.CartId
                                                  && ticketCart.IsDeleted == false
                                            select ticketCart).FirstOrDefault();
                    payment.Note = selectTicketCart.Note;
                    if (item.IsComplete == true)
                    {
                        payment.StatusOfPayment = "Đã hoàn thành";
                    }
                    else
                    {
                        payment.StatusOfPayment = "Chưa hoàn thành";
                    }
                    var selectScheduleId = (from ticket in _entities.Tickets
                                            where ticket.CartId == item.CartId
                                                  && ticket.IsDeleted == false
                                                  && ticket.Status == true
                                            select ticket.ScheduleId).FirstOrDefault();
                    Schedule selectSchedule = new Schedule();
                    selectSchedule = (from schedule in _entities.Schedules
                                          where schedule.ScheduleId == selectScheduleId
                                          select schedule).FirstOrDefault();
                    if (selectSchedule != null)
                    {
                        var selectTheaterName = (from theater in _entities.Theaters
                                                 where theater.TheaterId == selectSchedule.TheaterId
                                                 select theater.TheaterName).FirstOrDefault();
                        payment.TheaterName = selectTheaterName;

                        var selectFilmName = (from film in _entities.Films
                                              where film.FilmId == selectSchedule.FilmId
                                              select film.Name).FirstOrDefault();
                        payment.FilmName = selectFilmName;

                        payment.Date = selectSchedule.Date.ToString("dd/MM/yyyy");

                        ShowTime selectShowTime = new ShowTime();
                        selectShowTime = (from showtime in _entities.ShowTimes
                                          where showtime.ShowTimeId == selectSchedule.ShowTimeId
                                          select showtime).FirstOrDefault();
                        var strShowTime = string.Empty;
                        if (selectShowTime.Time.Hours < 10)
                        {
                            strShowTime = strShowTime + "0" + selectShowTime.Time.Hours;
                        }
                        else
                        {
                            strShowTime = strShowTime + selectShowTime.Time.Hours;
                        }
                        if (selectShowTime.Time.Minutes < 10)
                        {
                            strShowTime = strShowTime + "0" + selectShowTime.Time.Minutes;
                        }
                        else
                        {
                            strShowTime = strShowTime + selectShowTime.Time.Minutes;
                        }
                        payment.ShowTime = strShowTime;
                    }
                    
                    listPayment.Add(payment);
                }
                adminHomeInfor.ListPaymentConfirm = listPayment;
                return adminHomeInfor;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}